package weixin.idea.extend.function.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.core.util.LogUtil;
import org.jeecgframework.core.util.StringUtil;

import weixin.guanjia.account.service.WeixinAccountServiceI;
import weixin.guanjia.core.entity.message.resp.TextMessageResp;
import weixin.guanjia.core.util.MessageUtil;
import weixin.idea.extend.function.KeyServiceI;
import weixin.idea.huodong.entity.HAcodeEntity;
import weixin.idea.huodong.entity.HAcodeHMEntity;
import weixin.idea.huodong.service.HAcodeServiceI;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 关键字：{1}激活码 功能类：weixin.idea.key.function.impl.ActivationCodeService
 * 描述：实现用户回复自动发放激活码，每人用户每个游戏只能领取一次
 * 
 * @author renlr
 */
public class HacodeService implements KeyServiceI {

	@Override
	public String getKey() {
		return "激活码";
	}

	@Override
	public String excute(String content, TextMessageResp textMessage, HttpServletRequest request) {
		String activCode = content.trim();
		String returnMessage = null;
		String code = String.valueOf("");
		String codeMsg = String.valueOf("");
		if (StringUtil.isNotEmpty(content)) {
			HAcodeServiceI hacodeService = (HAcodeServiceI) ApplicationContextUtil.getContext().getBean("haCodeService");
			WeixinAccountServiceI weixinAccountService = (WeixinAccountServiceI) ApplicationContextUtil.getContext().getBean("weixinAccountService");
			String sys_accountId = weixinAccountService.findByToUsername(textMessage.getFromUserName()).getId();
			HAcodeEntity hacode = findKey(content, sys_accountId, hacodeService);
			if (hacode != null) {
				HAcodeHMEntity hacodeHM = hacodeService.findHAcodeHMEntity(textMessage.getToUserName(), hacode);
				if (hacode != null && hacode.getSurplus() != null && hacode.getSurplus() <= 0)
					codeMsg = String.valueOf("已领完");
				if (hacodeHM != null)
					codeMsg = String.valueOf("已领取");
				if (hacodeHM == null && code.length() == 0 && hacode.getSurplus() > 0) {
					JSONArray array = JSONArray.parseArray(hacode.getContent());
					if (array != null) {
						JSONObject $json = new JSONObject();
						Iterator<Object> it = array.iterator();
						while (it.hasNext()) {
							JSONObject json = (JSONObject) it.next();
							if (json.getInteger("s") != null && json.getInteger("s") == Integer.valueOf(0)) {
								code = json.getString("n");
								json.put("s", 1);
								$json = json;
								array.remove(json);
								break;
							}
						}
						array.add($json);
						hacode.setContent(array.toJSONString());
						hacode.setSurplus(hacode.getSurplus() - 1);
						hacodeHM = new HAcodeHMEntity();
						hacodeHM.setHaid(hacode.getId());
						hacodeHM.setOpendid(textMessage.getToUserName());
						hacodeHM.setNumbers(code);
						hacodeHM.setAddtime(new Date());
						hacodeHM.setAccountid(sys_accountId);
						hacodeService.save(hacodeHM);
						hacodeService.saveOrUpdate(hacode);
					}
				}
			} else {
				codeMsg = String.valueOf("没有活动");
			}
		}
		if ("".equals(activCode)) {
			returnMessage = getTranslateUsage();
		} else {
			if (StringUtil.isNotEmpty(codeMsg) || StringUtil.isEmpty(code)) {
				returnMessage = "你选的游戏暂时没有库存了!公众号会即时更新资讯，请随时关注我们的动态哦!";
			} else {
				returnMessage = "恭喜您领取到奖品：" + code;
			}
		}
		textMessage.setContent(returnMessage);
		return MessageUtil.textMessageToXml(textMessage);
	}

	private HAcodeEntity findKey(String keyworlds, String sys_accountId, HAcodeServiceI hacodeService) {
		List<HAcodeEntity> hacodeList = hacodeService.findByProperty(HAcodeEntity.class, "accountid", sys_accountId);
		LogUtil.info("---------sys_accountId----关键字查询结果条数：----" + hacodeList != null ? hacodeList.size() : 0);
		for (HAcodeEntity r : hacodeList) {
			// 如果包含关键字
			String kw = r.getGamename();
			String[] allkw = kw.split(",");
			for (String k : allkw) {
				if (keyworlds.startsWith(k)) {
					LogUtil.info("---------sys_accountId----查询结果----" + r.getGamename());
					return r;
				}
			}
		}
		return null;
	}

	/**
	 * 使用指南
	 * 
	 * @return
	 */
	public static String getTranslateUsage() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("回复游戏名称获取激活码,每个用户单个游戏只能获取一次").append("\n\n");
		return buffer.toString();
	}

}
